package com.lm56.web.security;


import com.lm56.common.Utils;
import com.lm56.web.sys.domain.User;
import com.lm56.web.sys.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by Kelvin Yeung on 2016/6/6.
 */
public class SecUserDetailsService implements UserDetailsService {

    private static Logger logger = LoggerFactory.getLogger(SecUserDetailsService.class);

    @Autowired
    UserService userService;


    public UserDetails loadUserByUsername(String userCode) throws UsernameNotFoundException {

        User user = null;
        //可以用email登录或电话号码登录
        if(Utils.isMobilePhoneNo(userCode)){

            user = userService.getUserByPhoneNo(userCode);
        }else if(Utils.isEmail(userCode)){
            user  = userService.getUserByEmail(userCode);

        }



        if(user == null){
            logger.warn("user is not exists", userCode);
            throw new UsernameNotFoundException("用户不存在！");

        }
        SecUserDetails userDetails = new SecUserDetails(userCode,user.getPassword(),user.getSalt(),user.getUserType(),true);
        userDetails.setUserId(user.getId());

        //加载权限资源
        Set<SimpleGrantedAuthority> authories = new HashSet<SimpleGrantedAuthority>();


        //分角色 SYS_ADMIN 系统管理员  USER_COMPANY 公司 USER_SENDER 发货人 USER_RECEIVER 收货人 USER_DRIVER 司机 USER_OTHER 其他
        //PLATFORM_USER 平台用户 注册了的用户都是平台用户
        switch (user.getUserType()){
            case User.USER_TYPE_COMPANY:
                authories.add(new SimpleGrantedAuthority("USER_COMPANY"));
                break;
            case User.USER_TYPE_SENDER:
                authories.add(new SimpleGrantedAuthority("USER_SENDER"));
                break;
            case User.USER_TYPE_RECEIVER:
                authories.add(new SimpleGrantedAuthority("USER_RECEIVER"));
                break;
            case User.USER_TYPE_DRIVER:
                authories.add(new SimpleGrantedAuthority("USER_DRIVER"));
                break;
            case User.USER_TYPE_OTHER:
                authories.add(new SimpleGrantedAuthority("USER_OTHER"));
                break;
                default:
                    break;
        }

        authories.add(new SimpleGrantedAuthority("PLATFORM_USER"));
        userDetails.setAuthorities(authories);


        return userDetails;
    }
}
